#include "ClientCollection.hpp"

ClientCollection* ClientCollection::instance = 0;

/** 
* Initializes a new instance of the ClientCollection class.
*/
ClientCollection::ClientCollection(){
    clientList = 0;
    clientCount = 0;
    MAX_CLIENTS = 0;
}

void ClientCollection::setup(int numClients, Map* map){
    //Setup client lists to empty
    MAX_CLIENTS = numClients;
	clientCount = 0;
	clientList = new Client[MAX_CLIENTS];
	for(int i = 0; i < MAX_CLIENTS; i++){
		clientList[i].index = i;
	}
}

/** 
* Get number of active clients.
*/
int ClientCollection::getClientCount(){
	return clientCount;
}

/** 
* Gets a pointer to an available Client that can be added.
* @return Pointer to Client to add.
*/
Client* ClientCollection::addClient(){
	//Find a free client
	for(int i = 0; i < MAX_CLIENTS; i++){
		if(!clientList[i].active){
			clientCount++;
			return &clientList[i];
		}
	}
	return 0;
}

/** 
* Removes the Client at specified index.
* @param index The index of Client to remove.
*/
void ClientCollection::removeClient(int index){
	if(clientList[index].active){
		clientCount--;
		clientList[index].active = false;
	}
}

/** 
* Remove client by pointer.
* @param client The Client to remove.
*/
void ClientCollection::removeClient(Client* client){
    removeClient(client->index);
}

void ClientCollection::bind(lua_State* luaState){
    luabind::module(luaState)[
        luabind::class_<ClientCollection>("ClientCollection")
            .def_readonly("clientCount", &ClientCollection::clientCount)
    ];
}

void ClientCollection::push(lua_State* luaState){
    luabind::object o = luabind::object(luaState, this);
    o.push(luaState);
}